package com.beaven.beavenime.activity.guide

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.provider.Settings
import android.support.v7.app.AppCompatActivity
import android.view.inputmethod.InputMethodManager
import com.beaven.beavenime.R
import com.beaven.beavenime.activity.MainActivity
import com.beaven.beavenime.utils.isThisImeEnabled
import com.beaven.beavenime.utils.isThisImeSwitchUse
import kotlinx.android.synthetic.main.activity_guide.*


class GuideActivity : AppCompatActivity() {

    private lateinit var imeEnableHandler: ImeEnableHandler
    private lateinit var imm: InputMethodManager

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_guide)
        imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imeEnableHandler = ImeEnableHandler(this, imm)
        bt_open_ime.setOnClickListener {
            invokeLanguageAndInputSettings()
            imeEnableHandler.sendEmptyMessageDelayed(
                ImeEnableHandler.CHECK_IME_ENABLE_WHAT,
                ImeEnableHandler.CHECK_IME_ENABLE_TIME
            )
        }
        bt_set_ime.setOnClickListener {
            imm.showInputMethodPicker()
        }
        if (isThisImeSwitchUse(this)) {
            startToMainActivity()
        }
    }

    override fun onStart() {
        super.onStart()
        registerReceiver(switchInputReceiver, IntentFilter(Intent.ACTION_INPUT_METHOD_CHANGED))
    }

    override fun onResume() {
        super.onResume()
        if (isThisImeEnabled(this, imm)) {
            bt_open_ime.isEnabled = false
        }
    }

    override fun onStop() {
        super.onStop()
        unregisterReceiver(switchInputReceiver)
    }

    private fun invokeLanguageAndInputSettings() {
        val intent = Intent()
        intent.action = Settings.ACTION_INPUT_METHOD_SETTINGS
        intent.addCategory(Intent.CATEGORY_DEFAULT)
        startActivity(intent)
    }

    private fun startToMainActivity() {
        startActivity(Intent(this@GuideActivity, MainActivity::class.java))
        finish()
    }

    /**
     * 监听输入法切换广播
     */
    private val switchInputReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            intent?.let {
                if (it.action == Intent.ACTION_INPUT_METHOD_CHANGED) {
                    if (isThisImeSwitchUse(this@GuideActivity) && isThisImeSwitchUse(this@GuideActivity)) {
                        startToMainActivity()
                    }
                }
            }
        }
    }
}
